package cn.tedu.m2;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂,并设置连接信息
        ConnectionFactory f1 = new ConnectionFactory();
        f1.setHost("192.168.64.140");
        f1.setPort(5672);
        f1.setUsername("admin");
        f1.setPassword("admin");
        Connection con = f1.newConnection(); //连接
        Channel c = con.createChannel(); //通信的通道
        //创建helloworld-XQ队列
        c.queueDeclare("helloworld-XQQ",true,false,false,null);

        //创建回调对象
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
               String s = new String(message.getBody());
                System.out.println("收到："+s);
                //模拟处理耗时消息
                //遍历字符串，每找到一个.字符，暂停1秒
                for(int i =0 ;i < s.length();i++){
                    if (s.charAt(i)=='.'){
                        try {
                            Thread.sleep(1000);
                        }catch (InterruptedException e){
                            System.out.println("有问题！");
                        }
                    }
                }
                //手动发送回执
                //c.basicAck(deliveryTag:回执，multiple:是否同时确认之前接收过的所有消息);
                c.basicAck(message.getEnvelope().getDeliveryTag(),false);
                System.out.println("-----------------消息处理完成");
            }
        };

        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };
        //每次只接收一条，在处理完之前不接收下一条
        c.basicQos(1);

        //接收消息
        c.basicConsume("helloworld-XQQ", false,deliverCallback,cancelCallback);
    }
}
